import {
  Card,
  Form,
  Select,
  Button,
  Input,
  Space,
  Radio,
  Upload,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import {
  useNavigate,
  useLocation,
} from "react-router-dom";
import styles from "./index.module.css";
import { useEffect, useState } from "react";
import {
  getChannels,
  addContent,
  getContentById,
  editContent,
} from "@requests/content";
//富文本插件
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

const Publish = () => {
  const [form] = Form.useForm();
  // 频道
  const [channels, setChannels] = useState([]);
  const getChannelsList = async () => {
    const res = await getChannels();
    setChannels(res.data.channels);
  };
  useEffect(() => {
    getChannelsList();
  }, []);
  // 上传图片
  let [fileList, setFileList] = useState([]);
  const onUploadChange = ({ fileList }: any) => {
    setFileList(fileList);
  };
  //点击单选 多选类型
  const [type, setType] = useState(1);
  const onTypeChange = (e: any) => {
    setType(e.target.value);
    setFileList([]);
  };
  // 添加/编辑提交
  const location = useLocation();
  const getId = location.search?.split("=")[1];

  const navigate = useNavigate();
  const onFinish = async (val: any) => {
    console.log(val);

    if (type !== fileList.length) {
      message.error("上传图片数量与类型不匹配");
      return;
    }
    // 组织提交数据
    const data = {
      ...val,
      cover: {
        type,
        images: fileList.map((item: any) => {
          return item?.response?.data?.url || item.url;
        }),
      },
    };
    getId ? await editContent(getId, data) : await addContent(data);
    navigate("/home/content");
  };

  // 获取修改文章的id
  const title = getId ? "修改文章" : "发布文章";
  const update = async () => {
    const res = await getContentById(getId);
    console.log(res);
    form.setFieldsValue({
      title: res.data.title,
      channel_id: res.data.channel_id,
      content: res.data.content,
    });
    setType(res.data.cover.type);
    setFileList(res.data.cover.images.map((item: any) => ({ url: item })));
  };
  useEffect(() => {
    if (getId) {
      update();
    }
  }, [getId]);
  return (
    <div className={styles.root}>
      <Card>
        <Form labelCol={{ span: 4 }} onFinish={onFinish} form={form}>
          <Form.Item
            label="文章标题："
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道："
            name="channel_id"
            rules={[{ required: true, message: "请选择所属频道" }]}
          >
            <Select
              style={{ width: 288 }}
              options={channels.map((province: any) => ({
                label: province.name,
                value: province.id,
              }))}
              placeholder="请选择文章频道"
            />
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item>
              <Radio.Group onChange={onTypeChange} value={type}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {type > 0 ? (
              <div style={{ marginTop: 16 }}>
                <Upload
                  name="image"
                  listType="picture-card"
                  action="http://toutiao.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onPreview={() => {}}
                  onChange={onUploadChange}
                >
                  {fileList.length < type ? (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  ) : null}
                </Upload>
              </div>
            ) : null}
          </Form.Item>
          <Form.Item
            label="文章内容："
            name="content"
            initialValue=""
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <ReactQuill placeholder="请输入文章内容" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {title}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
